package com.pmt.feedplayer.di

import com.pmt.feedplayer.translate.TranslationController
import com.pmt.feedplayer.translate.PlayerManager
import com.pmt.feedplayer.translate.iOSAudioExtractor
import com.pmt.feedplayer.translate.iOSSpeechRecognizer
import com.pmt.feedplayer.translate.iOSTranslationService
import platform.Foundation.NSObject

actual class DependencyContainer {
    
    // 使用懒加载初始化播放器管理器
    private val playerManager by lazy { PlayerManager.getInstance() }
    
    // 翻译控制器缓存
    private val translationControllers = mutableMapOf<String, TranslationController>()
    
    /**
     * 获取播放器控制器实例
     * @param videoId 视频唯一标识符，用于创建独立的翻译控制器
     */
    actual fun getPlayerController(videoId: String): TranslationController {
        return translationControllers.getOrPut(videoId) {
            createTranslationController()
        }
    }
    
    /**
     * 创建新的翻译控制器实例
     */
    private fun createTranslationController(): TranslationController {
        return TranslationController(
            audioExtractor = iOSAudioExtractor(),
            speechRecognizer = iOSSpeechRecognizer(NSObject()),
            translator = iOSTranslationService(),
            subtitleManager = iOSSubtitleManager(),
            scope = CoroutineScope(Dispatchers.Main)
        )
    }
    
    /**
     * 获取播放器管理器实例
     */
    actual fun getPlayerManager(): PlayerManager {
        return playerManager
    }
    
    /**
     * 释放特定视频的资源
     * @param videoId 视频唯一标识符
     */
    actual fun releaseVideoResources(videoId: String) {
        translationControllers[videoId]?.let {
            it.stopTranslation()
            translationControllers.remove(videoId)
        }
    }
    
    /**
     * 释放所有资源
     */
    actual fun release() {
        // 停止所有翻译控制器
        translationControllers.values.forEach { it.stopTranslation() }
        translationControllers.clear()
        
        // 释放播放器管理器
        playerManager.release()
    }
}